%%--------------------------------------------------------------------
%% Author: <vjache>
%% Created: 30.03.2009
%% Description: Iterator over mnesia vector(table) by query. Query can 
%%				be either atom 'all'(traverse each record) or tuple 
%%				{lookup,Key}(traverse each record having key Key).
%%--------------------------------------------------------------------
-module(iter_vect_query).

%%--------------------------------------------------------------------
%% Include files
%%--------------------------------------------------------------------
-include("../include/iter.hrl").
%%--------------------------------------------------------------------
%% Exported Functions
%%--------------------------------------------------------------------
-export([
		 new/2,
		 open/1,
		 next/1,
		 close/1,
		 test/1
		 ]).

%%--------------------------------------------------------------------
%% API Functions
%%--------------------------------------------------------------------

new(Vect,Query) ->
	iter:from_module(?MODULE, {Vect,Query}).

open({Vect,Query}) ->
	VectSess=vect:open(Vect),
	IterState=case Query of
		all ->
			iter:open(vect:all(VectSess));
		{lookup,Key} ->
			iter:open(vect:lookup(VectSess,Key))
	end,
	{VectSess,IterState}.

next({VectSess,IterState}) ->
	{IterNewState,Item}=iter:next(IterState),
	{{VectSess,IterNewState},Item}.
close({VectSess,IterState}) ->
	ok=iter:close(IterState),
	ok=vect:close(VectSess).

%%--------------------------------------------------------------------
%% Test Functions
%%--------------------------------------------------------------------

test(Query) ->
	I=new(vect_mnesia:new(ring,[]),Query),
	iter:foreach(I,fun(E)->
						   io:format("~p~n",[E])
				 end),
	ok.

%%--------------------------------------------------------------------
%% Local Functions
%%--------------------------------------------------------------------